<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2018/12/22
 * Time: 下午5:54
 */

namespace App\Http\Controllers;

use App\Http\Model\Hint;
use App\Http\Model\Meet;
use App\Http\Model\OutJson;
use App\Http\Model\Room;
use App\Http\Model\Union;
use App\Http\Model\User;
use App\Http\Services\ContentCheckServices;
use App\Http\Services\MsgServices;
use App\Http\Services\RoomHotServices;
use App\Http\Services\RoomMsgServices;
use App\Http\Services\RoomServices;
use App\Http\Services\RoomUserServices;
use App\Http\Services\SystemConfigServices;
use App\Http\Services\UserServices;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use App\Http\Services\TrendsServices;
// use App\Http\Services\RoomVoiceCheckServices;
use App\Lib\Search;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\Lib\Response;
use App\Http\Services\ActivityServices;
use App\Http\Services\ZegoServices;
use Carbon\Carbon;
use App\Http\Model\RoomMicro;
use App\Http\Services\NewRoomMicroServices;

class RoomController extends BaseController
{
    private $services_room;
    private $room_user_services;
    private $room_msg_services;
    private $msg_services;
    private $services_room_hot;
    private $services_users;
    protected $trendsServices;
    private $contentCheckServices;
    // private $room_voice_check_services;
    protected $activityServices;
    protected $zegoService;
    protected $newRoomMicroService;

    protected $model_union;

    protected $anchorStartLiveTime = 'MICLIVE:START:USER:'; //主播上麦缓存 MICLIVE:START:USER: userid=>time string
    protected $anchorLiveTime = 'MICLIVETIME:USER:';//主播开播总时间秒 MICLIVETIME:USER: userid=>int 

    public function __construct()
    {
        $this->services_room = new RoomServices();
        $this->room_user_services = new RoomUserServices();
        $this->room_msg_services = new RoomMsgServices();
        $this->msg_services = new MsgServices();
        $this->services_room_hot = new RoomHotServices();
        $this->services_users = new UserServices();
        $this->trendsServices = new TrendsServices();
        $this->contentCheckServices = new ContentCheckServices();
        // $this->room_voice_check_services = new RoomVoiceCheckServices();
        $this->activityServices = new ActivityServices();
        $this->zegoService = new ZegoServices();
        $this->newRoomMicroService = new NewRoomMicroServices();
        $this->model_union = new Union();
    }


    /**
     * 获取房间信息
     * @param Request $request
     */
    public function info(Request $request)
    {
        $room_id = $request->get("room_id");
        if ($room_id == null) {
            Response::returnResult(Hint::PARAM_ERROR);
            return;
        }
        $data = $this->services_room->info($room_id);
        if ($data === null) {
            Response::returnResult(Hint::LOGIN_OUT);
            return;
        }
        if ($data === Hint::ROOM_NO_EXIST) {
            Response::returnResult(Hint::ROOM_NO_EXIST);
            return;
        }
        if ($data === Hint::ROOM_USER_IS_EXIST) {
            Response::returnResult(Hint::ROOM_USER_IS_EXIST);
            return;
        }
        if ($data === Hint::ROOM_USER_SHOT_OFF) {
            Response::returnResult(Hint::ROOM_USER_SHOT_OFF);
            return;
        }
        if ($data === Hint::ROOM_NOT_OPEN) {
            Response::returnResult(Hint::ROOM_NOT_OPEN);
            return;
        }

        Response::returnResult(Hint::SUCCESS, $data);
    }


    /**
     * 开启房间接口
     * @param Request $request
     */
    public function open(Request $request)
    {
        //增加限制房间开启
        $roomAndVolumeCloseConfig = (new SystemConfigServices())->getRoomAndVolumeCloseConfig();
        $currentTime = time();
        if ($roomAndVolumeCloseConfig[0] > 0 && $roomAndVolumeCloseConfig[1] > 0
            && $currentTime > $roomAndVolumeCloseConfig[0] && $currentTime < $roomAndVolumeCloseConfig[1]){
            Response::returnResult(Hint::ERR_SYS_FAIL, null, '当前不能开启房间');
        }

        if (!$request->post("room_id")) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $room_id = $request->post("room_id");
        $admin_id = $request->post("admin_id");
        $name = $request->post("name");
        $notice = $request->post("notice");
        $image = $request->post("image");
        $desc = $request->post("desc");
        $type_id = null;//$request->post("type_id");//参考room_type表
        $free_micro = $request->post("free_micro");
        $modeType = $request->post('mode_type');
        $room_tag_id = $request->post("room_tag_id");
        $room_mode = (int) $request->post("room_mode");//房间模式 1=正常 2=你说我猜 3=飞行棋 4=数字炸弹 5=团战模式

        //新增区服-段位提交
        $game_area = $request->post("game_area"); //区服
        $game_level = $request->post("game_level"); //段位

        $background_pic = $request->post('background_pic', ''); // 房间背景
        //添加内容检测
        $checkResult = $this->checkRoomContent($request, $name, $notice, $image, $desc);

        $data = $this->services_room->open($room_id, $name, $notice, $image, $desc, $type_id, $free_micro
                    , $modeType, $room_tag_id, $firstOpenFlag, $setNameSuccess, $room_mode, $game_area
                    , $game_level, $background_pic,$admin_id);
        if(is_numeric($data) && $data!=Hint::SUCCESS) {
            Response::returnResult($data);
        }

        // 默认设置房间名称成功标识
        $returnData = ['set_name_success' => 1];
        if (!$setNameSuccess) {
            $returnData = ['set_name_success' => 0];
        }

        Response::returnResult(Hint::SUCCESS, $returnData);
    }


    /**
     * 编辑房间信息
     * @param Request $request
     */
    public function edit(Request $request)
    {
        if (!$request->post("room_id")) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $room_id = $request->post("room_id");
        $name = $request->post("name");
        $notice = $request->post("notice");
        $image = $request->post("image");
        $desc = $request->post("desc");
        $room_tag_id = $request->post("room_tag_id");
        $type_id = $request->post("type_id");
        $game_area = $request->post("game_area");
        $game_level = $request->post("game_level");
        $room_mode = (int) $request->post("room_mode");//房间模式 1=正常 2=你说我猜 3=飞行棋 4=数字炸弹 5=团战模式
        //国庆期间不允许修改昵称和头像
        list($forbiddenStart, $forbiddenEnd) = SystemConfigServices::getForbiddenTimeForUpdate();
        if(time()>=$forbiddenStart && time() <= $forbiddenEnd){
            if(!empty($name) || !empty($image)){
                Response::returnResult(Hint::NATIONAL_FORBID_UPDATE);
            }
        }
        //添加内容检测
        $checkResult = $this->checkRoomContent($request, $name, $notice, $image, $desc);

        $data = $this->services_room->edit($room_id, $name, $notice, null, $desc, $room_tag_id, $room_mode, $game_area, $game_level, $type_id);
        if ($data === Hint::LOGIN_OUT) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
        if ($data === Hint::AUTH_ERROR) {
            Response::returnResult(Hint::AUTH_ERROR);
        }
        if ($data === Hint::ROOM_ACTION_TYPE_SELECT_ERROR) {
            Response::returnResult(Hint::ROOM_ACTION_TYPE_SELECT_ERROR);
        }
        if ($data === Hint::ROOM_ACTION_TYPE_TIME_LIMIT_ERROR) {
            Response::returnResult(Hint::ROOM_ACTION_TYPE_TIME_LIMIT_ERROR);
        }
        if ($data === Hint::ERR_DATA_UPDATE_FAIL) {
            Response::returnResult(Hint::ERR_DATA_UPDATE_FAIL);
        }

        if ($data === Hint::WAIT_OPEN) {
            Response::returnResult(Hint::WAIT_OPEN);
        }

        if ($data === Hint::ROOM_TYPE_SELECT_ERROR) {
            Response::returnResult(Hint::ROOM_TYPE_SELECT_ERROR);
        }

        if ($data === 'SET_NAME_FALSE') {
            Response::returnResult(Hint::ERR_FAIL, [], '今日房间名称更新次数已达上限');
        }
        if ($data === 'ROOM_IMAGE_EXAMINE_FALSE') {
            Response::returnResult(Hint::ERR_FAIL, [], '今日房间封面上传次数已达上限');
        }

        $contentCheckSwitch = $this->contentCheckServices->getContentCheckSwitch();
        if (!$contentCheckSwitch) {
            if ($name != null) {
                $this->room_msg_services->broadcast_edit_name($room_id, $name);
            }
            if ($notice != null) {
                $this->room_msg_services->broadcast_edit_notice($room_id, $notice);
            }
            if ($image != null) {
                $this->room_msg_services->broadcast_edit_image($room_id, $image);
            }
        }

        if ($type_id != null) {
            $this->room_msg_services->broadcast_edit_type_id($room_id, $type_id, $game_area, $game_level);
        }

        $roomData = (new Room())->get_room($data['room_id']);
        if(!empty($image) && $roomData['image'] != $image){
            Response::returnResult(Hint::ROOM_IMAGE_VERIFY);
        }else{
            Response::returnResult(Hint::SUCCESS);
        }
    }


    /**
     * 房间管理员权限列表
     * @param Request $request
     */
    public function get_roles(Request $request)
    {
        if (!$request->get("room_id")) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $room_id = $request->get("room_id");
        $page_index = $request->get("page_index");
        $page_size = $request->get("page_size");

        if (!$request->get('user_id')) {
            $user_id = 0;
        }
        if (!$request->get('page_index')) {
            $page_index = 0;
        }

        $data = $this->services_room->get_roles($room_id, $page_index, $page_size);

        if ($data === Hint::LOGIN_OUT) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
        if ($data === Hint::AUTH_ERROR) {
            Response::returnResult(Hint::AUTH_ERROR);
        }
        Response::returnResult(Hint::SUCCESS, $data);
    }

    /**
     * 房间管理员设置
     * @param Request $request
     */
    public function post_role(Request $request)
    {
        if (!$request->get('room_id')) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if (!$request->get('user_id')) {
            Response::returnResult(Hint::PARAM_ERROR);
        }

        $user_id = $request->get("user_id");
        $room_id = $request->get("room_id");
        $data = null;
        $current_user_id = 0;
        if (!$request->get("action")) {
            $data = $this->services_room->add_role($room_id, $user_id ,$current_user_id);
        } else {
            $data = $this->services_room->del_role($room_id, $user_id);
        }

        if ($data === Hint::LOGIN_OUT) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
        if ($data === Hint::AUTH_ERROR) {
            Response::returnResult(Hint::AUTH_ERROR);
        }
        if ($data === Hint::ROOM_ROLE_ROOM_MAX) {
            Response::returnResult(Hint::ROOM_ROLE_ROOM_MAX);
        }
        if($data === Hint::ROOM_ROLE_INVITE_AGAIN){
            Response::returnResult(Hint::ROOM_ROLE_INVITE_AGAIN);
        }
        if($data === Hint::ROOM_ROLE_ADMIN){
            Response::returnResult(Hint::ROOM_ROLE_ADMIN);
        }
        if (!$request->get("action")) {
            $this->room_msg_services->broadcast_role($room_id, $user_id);
            $this->msg_services->role_add($user_id, $room_id);
            //临时隐藏功能
            //$this->msg_services->roomAdminInvite($room_id ,$current_user_id ,$user_id ,0);
        } else {
            $this->room_msg_services->broadcast_unrole($room_id, $user_id);
        }

        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * 删除房间所有管理
     * @param Request $request
     */
    public function del_all_role(Request $request)
    {
        if (!$request->get('room_id')) {
            Response::returnResult(Hint::PARAM_ERROR);
            return;
        }

        $user = $this->services_users->get_current_user();
        if (empty($user)) {
            Response::returnResult(Hint::LOGIN_OUT);
            return;
        }

        $roomId = $request->get('room_id');
        $role = (new Room())->get_role($roomId, $user['user_id']);//读取当前用户权限
        if ($role != 2) { //非房主不能操作
            Response::returnResult(Hint::AUTH_ERROR);
        }

        $this->services_room->del_all_role($roomId); //删除所有管理员

        write_log("room", 'del_all_role', ['msg' => '删除所有管理', 'room_id' => $roomId]);
        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * 房间黑名单列表
     * @param Request $request
     */
    public function get_blocks(Request $request)
    {
        if (!$request->get("room_id")) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $room_id = $request->get("room_id");
        $page_index = $request->get("page_index");
        $page_size = $request->get("page_size");
        
        if (!$request->get('page_index')) {
            $page_index = 0;
        }

        $data = $this->services_room->get_blocks($room_id, $page_index, $page_size);
        if ($data === Hint::LOGIN_OUT) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
        if ($data === Hint::AUTH_ERROR) {
            Response::returnResult(Hint::AUTH_ERROR);
        }
        Response::returnResult(Hint::SUCCESS, $data);
    }

    /**
     * 房间黑名单设置
     * @param Request $request
     */
    public function post_block(Request $request)
    {
        if (!$request->get('room_id')) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if (!$request->get('user_id')) {
            Response::returnResult(Hint::PARAM_ERROR);
        }

        $user_id = $request->get("user_id");
        $room_id = $request->get("room_id");
        $data = null;
        if (!$request->get("action")) {
            $data = $this->services_room->add_block($room_id, $user_id);
        } else {
            $data = $this->services_room->del_block($room_id, $user_id);
        }

        if ($data === Hint::LOGIN_OUT) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
        if ($data === Hint::AUTH_ERROR) {
            Response::returnResult(Hint::AUTH_ERROR);
        }
        if (!$request->get("action")) {
            $this->room_msg_services->broadcast_block($room_id, $user_id);
        } else {
            $this->room_msg_services->broadcast_unblock($room_id, $user_id);
        }

        $current_user = $this->services_users->get_current_user();
        $data['block_time'] = time(); //操作时间
        $data['admin'] = [
            'user_id' => $current_user['user_id'] ?? 0,
            'user_uid' => $current_user['user_uid'] ?? "",
            'nickname' => $current_user['nickname'] ?? "",
        ];

        Response::returnResult(Hint::SUCCESS, $data);
    }


    /**
     * 收藏列表
     * @param Request $request
     */
    public function get_collects(Request $request)
    {
        $page_index = $request->get("page_index");
        $page_size = $request->get("page_size");

        if ($page_index === null) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if (empty($page_size)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }

        $data = $this->services_room->get_collects($page_index, $page_size);

        if ($data === Hint::LOGIN_OUT) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
        Response::returnResult(Hint::SUCCESS, $data);
    }

    /**
     * 房间收藏设置
     * @param Request $request
     */
    public function post_collect(Request $request)
    {
        $room_id = $request->get("room_id");
        if(empty($room_id)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $loginUserId = $this->getLoginUserId();//获取用户id
        if (empty($loginUserId)){
            Response::returnResult(Hint::LOGIN_OUT);
        }

        $data = null;
        if (!$request->get("action")) {
            $data = $this->services_room->add_collect($loginUserId, $room_id);
        } else {
            $data = $this->services_room->del_collect($loginUserId, $room_id);
        }
        if($data == Hint::ROOM_COLLECTED){
            Response::returnResult(Hint::ROOM_COLLECTED);
        }
        Response::returnResult(Hint::SUCCESS);
    }


    /**
     * 设置背景图片
     * @param Request $request
     */
    public function put_background(Request $request)
    {
        $room_id = $request->post("room_id");
        $pic_url = $request->post("pic_url");
        if (empty($room_id)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if (empty($pic_url)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $data = $this->services_room->set_background($room_id, $pic_url);

        Response::returnResult($data['code'], $data['data'], $data['msg']);
    }


    /**
     * 获取背景图片列表
     * @param Request $request
     */
    public function get_backgrounds(Request $request)
    {
        $data = $this->services_room->get_backgrounds();
        Response::returnResult(Hint::SUCCESS, $data);
    }

    /**
     * 获取背景图片列表
     * @param Request $request
     */
    public function get_backgrounds_v2(Request $request)
    {
        $roomId = intval($request->input('room_id', 0));
        $data = $this->services_room->get_backgrounds_v2($roomId);
        Response::returnResult(Hint::SUCCESS, $data);
    }


    /**
     * 踢出用户
     * @param Request $request
     */
    public function post_shotoff(Request $request)
    {
        $room_id = $request->get("room_id");
        $user_id = $request->get("user_id");
        if (empty($room_id)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if (empty($user_id)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }

        //校验
        $checkRes = $this->newRoomMicroService->checkRoomUserCanQuit($room_id, $user_id);
        if($checkRes['code'] != Hint::SUCCESS) {
            if($checkRes['code'] == Hint::ROOM_MICRO_USER_LOCK) {
                Response::returnResult(Hint::ROOM_MICRO_USER_LOCK, [], '已被锁麦，请先解锁');
            }
            if($checkRes['code'] == Hint::ROOM_PAIPAI_LOCK) {
                Response::returnResult(Hint::ROOM_PAIPAI_LOCK);
            }
        }

        $shotoff_time = 0;
        $data = $this->services_room->add_shotoff($room_id, $user_id, $shotoff_time);
        if ($data === Hint::AUTH_ERROR) {
            Response::returnResult(Hint::AUTH_ERROR);
        }
        if ($data === Hint::LOGIN_OUT) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
        $this->room_msg_services->command_user_out($room_id, $user_id, $shotoff_time);

        //用户离开房间数据处理
        $result = $this->newRoomMicroService->roomUserQuitForData($room_id, $user_id);

        Response::returnResult(Hint::SUCCESS);
    }


    /**
     * 获取随机个数房间
     * @param Request $request
     */
    public function get_random_rooms(Request $request)
    {
        $count = $request->get("count");
        if ($count === null) {
            Response::returnResult(Hint::PARAM_ERROR);
            return;
        }
        $data = $this->services_room->get_random_rooms($count);
        Response::returnResult(Hint::SUCCESS, $data);
    }


    /**
     * 获取房间列表 按类型获取
     * @param Request $request
     */
    public function get_rooms(Request $request)
    {
        $type_id = $request->get("type_id");
        $page_index = $request->get("page_index");
        $page_size = $request->get("page_size");

        if ($type_id === null) {
            Response::returnResult(Hint::PARAM_ERROR);
            return;
        }
        if ($page_index === null) {
            Response::returnResult(Hint::PARAM_ERROR);
            return;
        }
        if (empty($page_size)) {
            Response::returnResult(Hint::PARAM_ERROR);
            return;
        }

        $data = $this->services_room->get_rooms($type_id, $page_index, $page_size);
        Response::returnResult(Hint::SUCCESS, $data);
    }


    public function get_rooms_by_ids(Request $request)
    {
        $ids = $request->get("ids");
        if (empty($ids)) {
            Response::returnResult(Hint::PARAM_ERROR);
            return;
        }
        $arr = explode(',', $ids);
        if (empty($arr)) {
            Response::returnResult(Hint::PARAM_ERROR);
            return;
        }
        $data = $this->services_room->get_rooms_by_ids($arr);
        Response::returnResult(Hint::SUCCESS, $data);
    }


    /**
     * 获取热门房间列表
     * @param Request $request
     */
    public function get_hot_rooms(Request $request)
    {
        $page_index = $request->get("page_index");
        $page_size = $request->get("page_size");

        if ($page_index === null) {
            Response::returnResult(Hint::PARAM_ERROR);
            return;
        }
        if (empty($page_size)) {
            Response::returnResult(Hint::PARAM_ERROR);
            return;
        }

        $data = $this->services_room->get_hot_rooms($page_index, $page_size);
        Response::returnResult(Hint::SUCCESS, $data);
    }


    /**
     * 获取最新房间列表
     * @param Request $request
     */
    public function get_new_rooms(Request $request)
    {
        $page_index = $request->get("page_index");
        $page_size = $request->get("page_size");

        if ($page_index === null) {
            Response::returnResult(Hint::PARAM_ERROR);
            return;
        }
        if (empty($page_size)) {
            Response::returnResult(Hint::PARAM_ERROR);
            return;
        }

        $data = $this->services_room->get_new_rooms($page_index, $page_size);
        Response::returnResult(Hint::SUCCESS, $data);
    }


    /**
     * 获取房间类型
     * @param Request $request
     */
    public function get_room_types(Request $request)
    {
        $certified = $request->get('certified');
        if (!isset($certified)) {
            $certified = -1;
        }
        $data = $this->services_room->get_room_types($certified);
        Response::returnResult(Hint::SUCCESS, $data);
    }


    /**
     * 获取房间首页图标列表
     * @param Request $request
     */
    public function get_room_home_icons(Request $request)
    {
        $data = $this->services_room->get_room_home_icons();
        Response::returnResult(Hint::SUCCESS, $data);
    }

    /**
     * 添加举报
     * @param Request $request
     */
    public function post_report(Request $request)
    {
        $room_id = $request->post("room_id");
        $report_type = $request->post("report_type");
        $pics = $request->post("pics");
        $describe = $request->post("describe");

        if (empty($room_id)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if (empty($report_type)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }

        if ($pics == null) {
            $pics = "";
        }
        if ($describe == null) {
            $describe = "";

        }

        $ret = $this->services_room->add_report($room_id, $report_type, $pics, $describe);
        if (!$ret) {
            Response::returnResult(Hint::LOGIN_OUT);
            return;
        }
        Response::returnResult(Hint::SUCCESS);
    }


    /**
     * 用户所在管理房间
     * @param Request $request
     */
    public function get_role_rooms(Request $request)
    {
        $data = $this->services_room->get_self_role_rooms();
        if ($data == Hint::LOGIN_OUT) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
        Response::returnResult(Hint::SUCCESS, $data);
    }

    /**
     * 生成推荐房间列表
     */
    public function build_rank()
    {
        $this->services_room->build_rank();
    }

    /**
     * 设置房间类型
     * @param Request $request
     */
    public function set_room_type(Request $request)
    {
        $room_id = (int)$request->post('room_id');
        $type = (int)$request->post('type');
        if (!$room_id || $type < 0) {
            Response::returnResult(Hint::PARAM_ERROR);
        }

        $res = $this->services_room->set_room_type($room_id, $type);
        if ($res == Hint::NOT_ALLOWED) {
            Response::returnResult(Hint::NOT_ALLOWED);
        }

        if ($res == Hint::ROOM_IS_CERTIFY) {
            Response::returnResult(Hint::ROOM_IS_CERTIFY);
        }

        if ($res == Hint::ROOM_RADIO_NOT_SET) {
            Response::returnResult(Hint::ROOM_RADIO_NOT_SET);
        }

        if ($res == Hint::USER_NOT_OWNER) {
            Response::returnResult(Hint::USER_NOT_OWNER);
        }
        if ($res == Hint::ROOM_TYPE_NOT_EXIST) {
            Response::returnResult(Hint::ROOM_TYPE_NOT_EXIST);
        }
        if ($res == Hint::ROOM_TYPE_NOT_ALLOWED) {
            Response::returnResult(Hint::ROOM_TYPE_NOT_ALLOWED);
        }
        Response::returnResult(Hint::SUCCESS);
    }


    /**
     * 清理待删除房间
     */
    public function clear_wait_close()
    {
        //$this->services_room->loopClose();
        for ($i = 0; $i < 100; $i++) {
            $roomId = $this->services_room->clear_wait_close();
            if (empty($roomId)) {
                continue;
            }
            $this->services_room_hot->closeRoom($roomId);
        }
    }

    /**
     * 创建背景音乐
     * @method POST
     * @param Request $request
     */
    public function created_room_music(Request $request)
    {
        $roomId = (int)$request->post('room_id', 0);
        $musicName = (string)$request->post('music_name', '');
        $musicAuthor = (string)$request->post('music_author', '');

        if (!$roomId || !$musicName || !$musicAuthor) {
            Response::returnResult(Hint::PARAM_ERROR);
        }

        $this->services_room->created_room_music($roomId, $musicName, $musicAuthor);
        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * 房间背景音乐
     * @method GET
     * @param Request $request
     * @return mixed
     */
    public function get_room_music_list_by_room_id(Request $request)
    {
        $roomId = (int)$request->get('room_id', 0);
        if (!$roomId) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        Response::returnResult(Hint::SUCCESS, $this->services_room->get_room_music_list_by_room_id($roomId));
    }


    /**
     * 设置房间开启聊天屏幕
     * @param Request $request
     */
    public function screen_open(Request $request)
    {
        $room_id = $request->get('room_id');
        $opened = $request->get('opened');
        if (empty($room_id)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if ($opened === null) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $data = $this->services_room->set_screen_opened($room_id, $opened);
        if ($data === Hint::AUTH_ERROR) {
            Response::returnResult(Hint::AUTH_ERROR);
        }
        if ($data === Hint::LOGIN_OUT) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
        $this->room_msg_services->broadcast_screen_opened($room_id, $opened);

        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * 设置房间全麦是否关闭
     * @param Request $request
     */
    public function volume_closed(Request $request)
    {
        //增加限制房间开启
        $roomAndVolumeCloseConfig = (new SystemConfigServices())->getRoomAndVolumeCloseConfig();
        $currentTime = time();
        if ($roomAndVolumeCloseConfig[2] > 0 && $roomAndVolumeCloseConfig[3] > 0
            && $currentTime > $roomAndVolumeCloseConfig[2] && $currentTime < $roomAndVolumeCloseConfig[3]){
            Response::returnResult(Hint::ERR_SYS_FAIL, null, '维护中，请耐心等待');
        }

        $room_id = $request->get('room_id');
        $closed = $request->get('closed');
        if (empty($room_id)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if ($closed === null) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $data = $this->services_room->set_volume_closed($room_id, $closed);
        if ($data === Hint::AUTH_ERROR) {
            Response::returnResult(Hint::AUTH_ERROR);
        }
        if ($data === Hint::LOGIN_OUT) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
        $this->room_msg_services->broadcast_volume_closed($room_id, $closed);

        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * 设置房间密码
     * @param Request $request
     */
    public function password(Request $request)
    {
        $room_id = $request->get('room_id');
        $password = $request->get('password');
        if (empty($room_id)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        if ($password !== null) {
            $password = trim($password);
        }
        if ($password === '') {
            $password = null;
        }
        $data = $this->services_room->set_password($room_id, $password);
        if ($data === Hint::AUTH_ERROR) {
            Response::returnResult(Hint::AUTH_ERROR);
        }
        if ($data === Hint::LOGIN_OUT) {
            Response::returnResult(Hint::LOGIN_OUT);
        }

        //todo 需要开启语音检测
        // $this->room_voice_check_services->addTask($room_id, 3600,  false);

        //设置密码
        $this->services_room_hot->setPassword($room_id);

        $this->room_msg_services->broadcast_password($room_id, $password);
        Response::returnResult(Hint::SUCCESS);
    }


    /**
     * 关闭房间
     * @param Request $request
     */
    public function close(Request $request)
    {
        $room_id = $request->get('room_id');
        if (empty($room_id)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $data = $this->services_room->close($room_id);
        if ($data === Hint::AUTH_ERROR) {
            Response::returnResult(Hint::AUTH_ERROR);
        }
        if ($data === Hint::LOGIN_OUT) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
        $this->room_msg_services->command_close($room_id);
        //更新热度
        $this->services_room_hot->closeRoom($room_id);
        Response::returnResult(Hint::SUCCESS);
    }


    /**
     * 设置名称
     * @param $room_id
     * @param $name
     */
    public function set_name(Request $request)
    {
        $room_id = $request->post('room_id');
        $name = $request->post('name');
        if (empty($room_id) || empty($name)) {
            Response::returnResult(Hint::PARAM_ERROR);
            return;
        }
        $this->services_room->set_name($room_id, $name, 1);
        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * 设置公告
     * @param $room_id
     * @param $notice
     */
    public function set_notice(Request $request)
    {
        $room_id = $request->post('room_id');
        $notice = $request->post('notice');
        if (empty($room_id) || empty($notice)) {
            Response::returnResult(Hint::PARAM_ERROR);
            return;
        }
        $this->services_room->set_notice($room_id, $notice);
        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * 设置说明
     * @param $room_id
     * @param $desc
     */
    public function set_desc(Request $request)
    {
        $room_id = $request->post('room_id');
        $desc = $request->post('desc');
        if (empty($room_id) || empty($desc)) {
            Response::returnResult(Hint::PARAM_ERROR);
            return;
        }
        $this->services_room->set_desc($room_id, $desc);
        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * 设置认证/取消认证
     * @param $room_id
     * @param $val
     */
    public function set_cert(Request $request)
    {
        $room_id = $request->post('room_id');
        $val = $request->post('val');
        if (empty($room_id) || !isset($val)) {
            Response::returnResult(Hint::PARAM_ERROR);
            return;
        }
        $this->services_room->set_cert($room_id, $val);

        //取消管理员身份
        if($val == 0){
            $this->services_room->del_all_role($room_id);
        }

        // 清除 es 缓存
        (new Search())->delRoom($room_id);
        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * 设置房间图片
     * @param $room_id
     * @param $type
     */
    public function set_image(Request $request)
    {
        $room_id = $request->post('room_id');
        $image = $request->post('image');
        if (empty($room_id) || empty($image)) {
            Response::returnResult(Hint::PARAM_ERROR);
            return;
        }
        $this->services_room->set_image($room_id, $image);
        Response::returnResult(Hint::SUCCESS);
    }


    /**
     * 进入房间确认
     * @param Request $request
     */
    public function joinConfirm(Request $request)
    {
        $user = $this->services_users->get_current_user();
        if (empty($user)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $roomId = $request->get('room_id');
        $isFromSearch = $request->get('is_from_search') ?? 0;   //是否来自搜索，1：是 0：否

        if (empty($roomId)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }

        //进入房间
        if ($this->room_user_services->callback_user_add($roomId, $user['user_id'])) {
            $this->room_msg_services->broadcast_user_into($roomId, $user['user_id']);
        }

        $isSearch = $isFromSearch ?? 0; //是否是搜索进来的用户的进厅判断条件
        //增加进厅记录
        $this->services_room->addJoinLog($roomId ,$user['user_id'], $isSearch);

        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * 融云回调
     * @param Request $request
     */
    public function rongcloudCallback(Request $request)
    {
        $callback_data = file_get_contents("php://input");
       // write_log('rongcloudcallback', 'rongcloud_callback', $callback_data);
        try {
            $callback_data = json_decode($callback_data, true);
        } catch (\Exception $e) {
            Response::returnResult(Hint::SUCCESS);
            return;
        }

        foreach ($callback_data as $value) {
            //网页的不处理
            if(!empty($value['os']) && $value['os']=='Websocket') {
                continue;
            }
            // 只处理真实用户ID
            if (!is_numeric($value['userid'])){
                continue;
            }
            if ($value['status'] == 1 || $value['status'] == 2) {
                $this->services_room->setRongCloudOffline($value['userid'], $value['time']);
                (new \App\Http\Model\RoomUser())->removeUserFromRongyun($value['userid']);
            } else {
                $this->services_room->setRongCloudOnline($value['userid'], $value['time']);
            }
        }
    }

    /**
     * 融云房间状态回调
     * @param Request $request
     */
    public function rongcloudRoomStatusCallback(Request $request) {
        $callback_data = file_get_contents("php://input");
         write_log('rc-room-status-callback', 'data', $callback_data);
    }


    /**
     * 获取声网Token
     * @param Request $request
     */
    public function getAgoraToken(Request $request)
    {
        $roomId = $request->get('room_id');
        if (empty($roomId)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $token = $this->services_room->getAgoraToken($roomId);
        Response::returnResult(Hint::SUCCESS, $token);
    }

    /**
     * 获取即构Token
     */
    public function getZegoToken(Request $request){
        $roomId = $request->get('room_id');
        if (empty($roomId)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $token = $this->zegoService->getZegoToken($roomId);
        Response::returnResult(Hint::SUCCESS, $token);
    }


    /**
     * 保活融云聊天室
     */
    public function keepRongCloudRoom()
    {
        $queueKey = 'RONGCLOUD:KEEP:QUEUE';
        $roomId = Redis::RPOP($queueKey);
        if (empty($roomId)) {
            $roomIdArr = $this->services_room->getOpenedRoomIdArr();
            foreach ($roomIdArr as $roomId) {
                Redis::LPUSH($queueKey, $roomId);
            }
        } else {
            $this->room_msg_services->keepRongCloud($roomId);
        }
        for ($i = 0; $i < 200; $i++) {
            $roomId = Redis::RPOP($queueKey);
            if (empty($roomId)) {
                break;
            }
            $this->room_msg_services->keepRongCloud($roomId);
        }
    }


    public function killAllRoom()
    {
        $roomIdArr = $this->services_room->getOpenedRoomIdArr();
        foreach ($roomIdArr as $roomId) {
            $this->room_msg_services->command_close($roomId);
            $this->services_room->clean($roomId);
        }
    }


    public function killRoom(Request $request)
    {
        $roomId = $request->post('room_id');
        if (empty($roomId)) {
            OutJson::outJsonNoData(Hint::PARAM_ERROR);
            return;
        }

        $this->room_msg_services->command_close($roomId);
        $this->services_room->clean($roomId);
        $this->services_room_hot->closeRoom($roomId);
        OutJson::outJsonResult(Hint::SUCCESS);

    }


    /**
     * loop离线用户处理
     */
    public function loopOffline()
    {
        $roomModel = new Room();//匹配功能需要用到
        $userModel = new User();
        $meetModel = new Meet();
        $logOutUserIds = $roomModel->getLogOutUserIds(0);
        if ($logOutUserIds) {
            foreach ($logOutUserIds as $userId => $ts) {
                if ($userModel->checkUserOnlineStatus($userId) || time() * 1000 >= $ts) {//用户登录了 或者 超过30分钟
                    $roomModel->deleteLogOutUserCache($userId);
                    $meetModel->deleteOnlineUserLevelCache($userId);
                }
            }
        }

        for ($i = 0; $i < 1000; $i++) {
            $userId = $this->services_room->getRongCloudOfflineTimeout();
            if (empty($userId)) {
                // sleep(1);
                continue;
            }
            $roomId = $this->room_user_services->getCurRoomId($userId);
            if(!empty($roomId)){
                //用户离开房间数据处理
                $result = $this->newRoomMicroService->roomUserQuitForData($roomId, $userId);
                if($result['code'] != Hint::SUCCESS) {
                    break;
                }

                //断开即构链接
                $this->zegoService->kickoutUser($userId, $roomId);
            }
        }
    }


    /**
     * 用户重新进入软件检查是否需要退出房间
     */
    public function checkLeaveRoom()
    {
        $user = $this->services_users->get_current_user();
        if (empty($user)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $userId = $user['user_id'];
        $roomId = $this->room_user_services->getCurRoomId($userId);
        if (empty($roomId)) {
            Response::returnResult(Hint::SUCCESS);
        }
        if(!empty($roomId)){
            //用户离开房间数据处理
            $result = $this->newRoomMicroService->roomUserQuitForData($roomId, $userId);
        }
        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * 房间详情
     * */
    public function roomDetail()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'roomDetail', $this->requestData);

        } while (false);

        $this->responseData();
    }

    ################# 后台调用 ##########################################

    /**
     * 房间推荐创建
     * */
    public function roomRecoCreate()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'roomRecoCreate', $this->requestData);

        } while (false);

        $this->responseData();
    }

    public function getRoomRecommend()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'getRoomRecommend', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 房间推荐更新
     * */
    public function roomRecoUpdate()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'roomRecoUpdate', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 房间推荐删除
     * */
    public function roomRecoRemove()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'roomRecoRemove', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 房间推荐热度系数创建或更新
     * */
    public function roomRecommendReplace()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'roomRecommendReplace', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 房间更新
     * */
    public function roomUpdate()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'roomUpdate', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 房间举报处理更新
     * */
    public function reportUpdate()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'reportUpdate', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 房间图片审核
     * */
    public function roomImageExamine()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'roomImageExamine', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 商品标签创建
     */
    public function labelCreate()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'labelCreate', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 商品标签编辑
     */
    public function labelEdit()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'labelEdit', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 房间标签创建
     * */
    public function roomTagCreate()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'roomTagCreate', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 房间标签更新
     * */
    public function roomTagUpdate()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'roomTagUpdate', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * CBD房间创建
     * */
    public function createRoomByCBD()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'createRoomByCBD', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * CBD房间修改
     */
    public function updateRoomByCBD()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'updateRoomByCBD', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 删除房间标签
     */
    public function labelDel()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'labelDel', $this->requestData);

        } while (false);

        $this->responseData();
    }


    /**
     * 设置房间话题
     * */
    public function setTopic()
    {
        do {
            if (!$this->checkRequest()) {
                break;
            }

            $this->callCommon($this->services_room, 'setTopic', $this->requestData);
            $roomId = $this->requestData['room_id'] ?? null;
            $topic = $this->requestData['topic'] ?? null;
            if (is_null($roomId) || is_null($topic)) {
                break;
            }
            $this->room_msg_services->broadcastChangeTopic($roomId, $topic);

        } while (false);

        $this->responseData();
    }


    /**
     * 获取踢人列表
     * */
    public function getShotoffLog()
    {
        do {
            if (!$this->checkRequest()) {
                break;
            }

            $this->callCommon($this->services_room, 'getShotoffLog', $this->requestData);

        } while (false);

        if(is_string($this->responseData)) $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    public function getErrorFormatter()
    {
        return self::$errorFormatter;
    }

    /*
    * 检测房间数据 检测数据包含
    * 文字-房间标题
    * 文字-房间公告
    * 文字-房间简介
    * 图片-房间封面
    * */
    public function checkRoomContent($request, &$name, &$notice, $image, &$desc)
    {
        $checkResult = $this->contentCheckServices->checkRoomContent($request->input());
        //初始化数据 不提交 进入审核机制
//        $name = (isset($checkResult['name']) && $name) ? $checkResult['name'] : "";
//        $notice = (isset($checkResult['notice']) && $notice) ? $checkResult['notice'] : "";
//        $image = (isset($checkResult['image']) && $image) ? $checkResult['image'] : "";
//        $desc = (isset($checkResult['desc']) && $desc) ? $checkResult['desc'] : "";
    }


    /**
     * 新版房间类型获取
     * */
    public function getRoomNewTypes()
    {
        do {
            if (!$this->checkRequest()) {
                break;
            }

            $this->callCommon($this->services_room, 'getRoomNewTypes', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 切换排麦方式消息通知
     * */
    public function changeMicroWayMsg()
    {
        do {
            if (!$this->checkRequest()) {
                break;
            }
            //查询房间是否是电台模式,不允许切换
            $roomInfo = $this->services_room->info($this->requestData['room_id']);
            if($roomInfo['room_type']['id'] == 44){
                $code = Hint::ERR_NORMAL;
                $msg = '电台房间不支持切换上麦模式';
                $data = [];   
                break;
            }
            if (!empty($this->requestData['room_id']) and isset($this->requestData['type']) and is_numeric($this->requestData['type'])) {
                $this->services_room->setFreeMicro($this->requestData['room_id'], $this->requestData['type']);

                $this->room_msg_services->changeMicroWayMsg([
                    'user_id' => $this->requestData['user_id'],
                    'room_id' => $this->requestData['room_id'],
                    'type' => $this->requestData['type'],
                ]);
            }

            $code = Hint::SUCCESS;
            $msg = Hint::getErrCodeMsg($code);
            $data = [];

        } while (false);
        $this->responseData = compact('code', 'msg', 'data');
        if(is_string($this->responseData)) $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    /**
     * 清空公屏消息
     * */
    public function clearScreenMsg()
    {
        do {
            if (!$this->checkRequest()) {
                break;
            }

            if (!empty($this->requestData['room_id'])) {
                $from = $this->requestData['from'] ?? 0; //0普通房间
                $role = 0;
                if(empty($from)){
                    //判断是否是管理员
                    $role = $this->services_room->get_user_role(['user_id' => $this->requestData['user_id'],
                            'room_id' => $this->requestData['room_id'],]
                    );
                }
                if($role ==0){
                    $code = Hint::AUTH_ERROR;
                    $msg = Hint::getErrCodeMsg($code);
                    $this->responseData = compact('code', 'msg', 'data');
                    break;
                }
                $this->room_msg_services->clearScreenMsg([
                    'user_id' => $this->requestData['user_id'],
                    'room_id' => $this->requestData['room_id'],
                ]);
            }

            $code = Hint::SUCCESS;
            $msg = Hint::getErrCodeMsg($code);
            $data = [];
            $this->responseData = compact('code', 'msg', 'data');

        } while (false);

        if(is_string($this->responseData)) $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    /**
     * xxx 收藏了房间消息
     * */
    public function collectRoomMsg(Request $request)
    {
        $roomId = $request->input('room_id');
        $userId = $request->input('user_id');
        if (!empty($roomId) and !empty($userId)) {
            $this->room_msg_services->collectRoomMsg($userId, $roomId);
        }

        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        $this->responseData = compact('code', 'msg', 'data');

        $this->responseData();
    }

    /**
     * xxx 欢迎xxx消息
     * */
    public function welcomeUserMsg(Request $request)
    {
        // $roomId = $request->input('room_id');
        // $userId = $request->input('user_id');
        // if (!empty($roomId) and !empty($userId)) {
            // $getUser = $this->services_users->get_current_user();
            // $this->room_msg_services->welcomeUserMsg($getUser['user_id'] ?? 0, $userId, $roomId);
        // }

        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        $this->responseData = compact('code', 'msg', 'data');

        $this->responseData();
    }


    /**
     * CMS-房间类型-添加/修改
     * */
    public function updateOrInsertRoomType()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'updateOrInsertRoomType', $this->requestData);

        } while (false);

        $this->responseData();
    }


    /**
     * CMS-房间类型-删除
     * */
    public function delRoomType()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'delRoomType', $this->requestData);

        } while (false);

        $this->responseData();
    }

    # ------------------------------------------------------------------------------------------

    /**
     * 根据房间ID获取麦上用户信息列表
     * @param Request $request
     * */
    public function microUserList(Request $request)
    {
        $this->responseData($this->services_room->microUserList($request->input()));
    }

    /**
     * 获取用户是否在麦上状态
     * @param Request $request
     * */
    public function getMicroUserState(Request $request)
    {
        $this->responseData($this->services_room->getMicroUserState($request->input()));
    }

    /**
     * 小屋速配便捷入口
     * */
    public function getRoomFastType()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'getRoomFastType', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 获取房间开厅时长
     */
    public function getOnlineTime(){
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'getOnlineTime', $this->requestData);

        } while (false);

        if(is_string($this->responseData)) $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    //后台配置车队权限
    public function setCarStatus(){
        do {
            if (!$this->checkRequest(false)) {
                break;
            }
            $this->callCommon($this->services_room, 'setCarStatus', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 增加私聊记录
     */
    public function addChatPrivateLog(){
        do {
            if (!$this->checkRequest()) {
                break;
            }
            $this->callCommon($this->services_room, 'addChatPrivateLog', $this->requestData);

        } while (false);

        if(is_string($this->responseData)) $this->responseData = json_decode($this->responseData, true);
        Response::returnResult($this->responseData['code'], $this->responseData['data'], $this->responseData['msg']);
    }

    /**
     * 分享
     */
    public function share(){
        do {
            if (!$this->checkRequest()) {
                break;
            }
            $this->callCommon($this->services_room, 'share', $this->requestData);

        } while (false);

        $this->responseData();
    }

    public function insertOrUpdateLabel(){
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'insertOrUpdateLabel', $this->requestData);

        } while (false);

        $this->responseData();
    }

    public function delRoomLabel(){
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'delRoomLabel', $this->requestData);

        } while (false);

        $this->responseData();
    }

    //取消未认证房间管理
    public function cmsCancelRole(){
        do {
            if (!$this->checkRequest(false)) {
                break;
            }
            $this->callCommon($this->services_room, 'cmsCancelRole', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**
     * 定时设置/取消设置 房间标签
     */
    public function timingHandleLabel(){
        do {
            if (!$this->checkRequest(false)) {
                break;
            }
            $this->callCommon($this->services_room, 'timingHandleLabel', $this->requestData);

        } while (false);

        $this->responseData();
    }

    /**小屋根据房间id获取房间详情
     * @param Request $request
     */
    public function get_rooms2_by_ids(Request $request)
    {
        $ids = $request->get("ids");
        if (empty($ids)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $arr = explode(',', $ids);
        if (empty($arr)) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $data = $this->services_room->get_rooms2_by_ids($arr);
        Response::returnResult(Hint::SUCCESS, $data);
    }

    /**
     * 用户同意/拒绝成为管理
     */
    public function adminApply(){
        do {
            if (!$this->checkRequest(true)) {
                break;
            }
            $res = $this->callCommon($this->services_room, 'adminApply', $this->requestData ,false);
            if($res['code'] == 0 ){
                $this->msg_services->roomAdminInvite($this->requestData['room_id'] ,$res['data']['send_user_id'] ,$this->requestData['user_id'] ,$this->requestData['status']);
                if($this->requestData['status'] == 1){
                    $this->room_msg_services->broadcast_role($this->requestData['room_id'] , $this->requestData['user_id']);
                    $this->msg_services->role_add($this->requestData['user_id'], $this->requestData['room_id']);
                }
            }else if($res['code'] == 1018){
                $this->msg_services->roomAdminInvite($this->requestData['room_id'] ,$res['data']['send_user_id'] ,$this->requestData['user_id'] ,3);
            }
        } while (false);

        $this->responseData();
    }

    /**
     * 设置房间动态封面
     */
    public function setDynamicBackground(){
        do {
            if (!$this->checkRequest(false)) {
                break;
            }
            $this->callCommon($this->services_room, 'setDynamicBackground', $this->requestData);
        } while (false);

        $this->responseData();
    }
    # ------------------------------------------------------------------------------------------

    public function createRoomLivePlan(Request $request) {

        $validator = Validator::make($request->all(),[
            // 'platform_id' => 'bail|required|integer',
            // 'host_id' => 'bail|required|integer|exists:user,user_id',
            'price' => 'bail|required|integer|min:1',
            'start_time' => 'bail|required|string',
            'end_time' => 'bail|required|string',
            'room_id' => 'bail|required|integer|exists:room,room_id',
            // 'follow_id' => 'bail|numeric|exists:user,user_id',
        ],[
            // 'platform_id.required' => '平台ID必须',
            // 'host_id.exists' => '主播不存在',
            'price.required' => '直播价格必须',
            'price.min' => '直播价格不可小于1',
            'start_time.required' => '直播开始时间必须',
            'end_time.required' => '直播结束时间必须',
            'room_id.required' => '直播房间必须',
            'room_id.exists' => '直播房间不存在',
        ]);
        if($validator->fails()){
            Log::debug($validator->errors()->first());
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $ret = $this->services_room->createOrUpdateRoomLivePlan($request->except('_url'));
    }

    public function removeRoomLivePlan(Request $request) {
        $id = $request->get('id', '');
        $this->services_room->deleteRoomLivePlan($id);
        Response::returnResult(Hint::SUCCESS);
    }

    public function getWealthValue(Request $request) {
        $this->trendsServices->checkToken();
        $roomId = $request->get('room_id', 0);
//        $res = $this->services_room->getWealth($roomId);
        $room_consumer = $this->model_union->getUnionRoomFinanceALL($roomId, '', '');
        $room_consumer_total = $room_consumer['total'] ??0;
        Response::returnResult(Hint::SUCCESS, (int)$room_consumer_total);
    }

    public function setUserInRoomTime(Request $request) {
        $user = $this->services_users->get_current_user();
        if (!empty($user)) {
            $roomId = (int) $request->get('room_id', 0);
            $second = (int) $request->get('second', 0);
            $userId = $user['user_id'];
            if(!empty($roomId)) {
                $this->services_room->setUserInRoomTime($roomId, (int) $userId, $second);
            }
        }

        Response::returnResult(Hint::SUCCESS);
    }


    public function setGodHaoSwitch(Request $request) {
        $validator = Validator::make($request->all(),[
            'room_id' => [ 'bail', 'required', 'integer', Rule::exists('room','room_id')->where(function($query) {
                $query->where('business_type', 1);
            })],
            'status' => 'bail|required|integer|in:0,1',
        ],[
            'room_id.required' => '参数错误',
            'room_id.integer' => '参数错误',
            'room_id.exists' => '房间不存在',
            'status.required' => '参数错误',
            'status.integer' => '参数错误',
            'status.in' => '参数错误',
        ]);
        if($validator->fails()){
            Response::returnResult(Hint::PARAM_ERROR, [], $validator->errors()->first());
        }

        $this->services_room->setGodHaoSwitch($request->post('room_id'), $request->post('status'));
        $this->room_msg_services->godHaoSwitchMsg($request->post('room_id'), $request->post('status'));
        Response::returnResult(Hint::SUCCESS);
    }


    /**
     * 获取房间信息 push
     */
    public function pushInfo()
    {
        do {
            if (!$this->checkRequest(false)) {
                break;
            }

            $this->callCommon($this->services_room, 'pushInfo', $this->requestData);

        } while (false);

        $this->responseData();
    }

    public function setDynamic(Request $request){
        $validator = Validator::make($request->all(),[
            'img' =>  'bail|required|string',
            'url' => 'bail|required|string',
            'name' => 'bail|required|string',
        ],[
            'img.required' => '参数错误',
            'img.string' => '参数错误',
            'url.required' => '参数错误',
            'url.string' => '参数错误',
            'name.required' => '参数错误',
            'name.string' => '参数错误',
        ]);
        if($validator->fails()){
            OutJson::outJsonCustom(Hint::PARAM_ERROR, $validator->errors()->first());
        }
        $id = $request->input('id')??0;
        if ($id){
            $res = $this->services_room->updateDynamic($id,$request->input('img'),$request->input('url'),$request->input('name'));
        }else{
            $res = $this->services_room->addDynamic($request->input('img'),$request->input('url'),$request->input('name'));
        }
        if (!$res){
            OutJson::outJsonNoData(Hint::ERROR);
        }
        OutJson::outJsonNoData(Hint::SUCCESS);
    }

    /**
     * 设置-房间公平是否展示礼物消息
     */
    public function setRoomPublicScreenGiftSwitch(Request $request)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        $roomId = $request->input('room_id') ?? 0;
        $switch_value = $request->input('switch_value') ?? 1;
        $switch_key = 'gift_show_switch';
        $res = $this->services_room -> setRoomSwitchCommon($roomId, $switch_key, $switch_value);
        if (!$res){
            $code = Hint::ERR_SYS_FAIL;
            $msg = '设置错误';
        }

        return compact('code', 'msg', 'data');
    }
    public function getRoomPublicScreenGiftSwitch(Request $request)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        $roomId = $request->input('room_id') ?? 0;
        $switch_key = 'gift_show_switch';
        $res = $this->services_room -> getRoomSwitchCommon($roomId, $switch_key);

        $data[$switch_key] = $res;
        return compact('code', 'msg', 'data');
    }


    public function delDynamic(Request $request){
        $id = $request->input('id')??0;
        if (!$id){
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $res = $this->services_room->delDynamic($id);
        if (!$res){
            Response::returnResult(Hint::ERROR);
        }
        Response::returnResult(Hint::SUCCESS);
    }

    public function getHotRoom(Request $request){
        $result = [
            'room_id' => 0
        ];
        $get_type = $request->get('type',0);//0默认所有CBD 1=去除拍拍电台的房间 2=拍拍房间
        $data = $this->activityServices->openRoomCbdAll($get_type);
        if(!empty($data)) {
            $key = array_rand($data);
            $result['room_id'] = $data[$key];
        }else{
            Response::returnResult(Hint::ERR_NORMAL, [], '暂无开启房间');
        }

        Response::returnResult(Hint::SUCCESS, $result);
    }

    /**
     * 房间模式编辑
     */
    public function modeEdit(Request $request)
    {
        if (!$request->post("room_id")) {
            Response::returnResult(Hint::PARAM_ERROR);
        }
        $room_id = $request->post("room_id");
        $room_mode = (int) $request->post("room_mode");//房间模式 1=正常 2=你说我猜 3=飞行棋 4=数字炸弹 5=团战模式
        $data = $this->services_room->edit($room_id, null, null, null, null, null, $room_mode);

        if ($data === Hint::LOGIN_OUT) {
            Response::returnResult(Hint::LOGIN_OUT);
        }
        if ($data === Hint::AUTH_ERROR) {
            Response::returnResult(Hint::AUTH_ERROR);
        }
        if ($data === Hint::ROOM_ACTION_TYPE_SELECT_ERROR) {
            Response::returnResult(Hint::ROOM_ACTION_TYPE_SELECT_ERROR);
        }
        if ($data === Hint::ROOM_ACTION_TYPE_TIME_LIMIT_ERROR) {
            Response::returnResult(Hint::ROOM_ACTION_TYPE_TIME_LIMIT_ERROR);
        }
        if ($data === Hint::ERR_DATA_UPDATE_FAIL) {
            Response::returnResult(Hint::ERR_DATA_UPDATE_FAIL);
        }

        if ($data === Hint::WAIT_OPEN) {
            Response::returnResult(Hint::WAIT_OPEN);
        }

        if ($data === Hint::ROOM_TYPE_SELECT_ERROR) {
            Response::returnResult(Hint::ROOM_TYPE_SELECT_ERROR);
        }
        (new Room())->get_room($room_id);

        Response::returnResult(Hint::SUCCESS);
    }

    /**
     * 一起玩房间列表
     */
    public function gameRoomList(Request $request)
    {
        $page = !empty((int)$request->get('page_index')) && $request->get('page_index') >= 0 ? (int)$request->get('page_index') : 0;
        $page_size = !empty((int)$request->get('page_size')) && $request->get('page_size') > 0 ? (int)$request->get('page_size') : 10;
        $room_mode = (int) $request->post("room_mode");//房间模式 1=正常 2=你说我猜 3=飞行棋 4=数字炸弹 5=团战模式

        $list = $this->services_room->gameRoomList($page, $page_size, $room_mode);

        Response::returnResult(Hint::SUCCESS, $list);
    }

    /**
     * 获取可加入的游戏房间
     */
    public function getCanPlayGameRoom(Request $request)
    {
        $room_mode = (int) $request->input("room_mode");//房间模式 1=正常 2=你说我猜 3=飞行棋 4=数字炸弹 5=团战模式

        $data = $this->services_room->getCanPlayGameRoom($room_mode);

        Response::returnResult(Hint::SUCCESS, $data);
    }

    /**
     * 新用户首次充值活动弹窗
     */
    public function popFirstRecharge(Request $request)
    {
        Response::returnResult(Hint::ROOM_POP_WISH_ERROR); 

        $guid = $request->get('guid');//设备标识
        $user = $this->services_users->get_current_user();
        if(empty($user))
        {
            Response::returnResult(Hint::ERR_USER_LOGIN_STATUS);  
        }

        //获取是否是新用户
        $res = $this->services_room->isFirstUser($user['user_id']);
        if(!empty($res)){
            //判断设备是否领取过
            if(empty($guid)){
                //获取用户guid
                $userInfo = $this->services_users->getUserData($user['user_id']);
                $guid = $userInfo['guid'];
            }
            $getstatus = $this->services_room->getIssetTicketLog($guid);
            if($getstatus)
            {
                Response::returnResult(Hint::ERROR,[],'该设备已经领取过!');  
            }
        }
        
        if(!empty($res))
        {
            Response::returnResult(Hint::SUCCESS,$res);  
        }else{
            Response::returnResult(Hint::ROOM_POP_WISH_ERROR,$res); 
        }
    }

    //获取用户是否充值状态,没有充值过弹窗
    public function userFirstRecharge(Request $request){
        
        $user = $this->services_users->get_current_user();
        if(empty($user))
        {
            Response::returnResult(Hint::ERR_USER_LOGIN_STATUS);  
        }
        //引导用户进行首充弹窗
        $res = $this->services_room->showFirstPop($user['user_id']);
        if(!empty($res))
        {
            Response::returnResult(Hint::SUCCESS,$res);  
        }else{
            Response::returnResult(Hint::ERROR,$res); 
        }
    }

    /**
     * 新用户获取抽奖券
     */
    public function getLuckTicket(Request $request)
    {
        $guid = $request->get('guid');//设备标识
        if(empty($guid))
        {
            Response::returnResult(Hint::ERROR,[],'缺少设备标识'); 
        }
        $user = $this->services_users->get_current_user();
        
        if(empty($user))
        {
            Response::returnResult(Hint::ERR_USER_LOGIN_STATUS);  
        }
        //判断设备是否领取过
        $getstatus = $this->services_room->getIssetTicketLog($guid);
        if($getstatus)
        {
            Response::returnResult(Hint::ERROR,[],'该设备已经领取过!');  
        }
        //获取是否是新用户
        $res = $this->services_room->getLuckTicket($user['user_id'],$guid);
        if(!empty($res))
        {
            Response::returnResult(Hint::SUCCESS,$res);  
        }else{
            Response::returnResult(Hint::ERROR,$res,'已经领取过奖励'); 
        }
    }
}
